package com.rfid.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

import com.entitymapper.EntityMapperException;
import com.entitymapper.EntityStatusException;
import com.rfid.RFIDCaller;
import com.rfid.client.LogEvent;
import com.rfid.dataSync.TraceInfoDataSyncListener;
import com.rfid.entityMapper.ProductFieldMapperToRead;
import com.rfid.entityMapper.TraceInfoFieldMapperToRead;
import com.rfid.jni.JNI_RFIDCaller;
import com.rfid.listener.LogListener;
import com.rfid.service.exception.ClientException;
import com.rfid.service.util.MapperUtils;
import com.teatrace.model.Product;
import com.teatrace.model.TraceInfo;

/**
 * 启动线程，进行读监听操作
 * @author hhf
 */
public class RFIDReadInfoService implements Runnable{
	
	private static final int RUNNING = 1;
	private static final int STOP = 2;
	private Integer state = STOP;
	private static RFIDReadInfoService instance = new RFIDDoReadService();
	private Thread thread;
	private MapperUtils utils;
	private List<LogListener> logListeners = new ArrayList<LogListener>();
	private static Logger log = Logger.getLogger(RFIDReadInfoService.class);
	
	
	
	static class RFIDDoReadService extends RFIDReadInfoService {
		
		private RFIDCaller caller = null;
		
		private static boolean status = false;
		
		public RFIDDoReadService() {
			try {
				this.caller = new JNI_RFIDCaller();
			} catch (IOException e) {
				throw new ClientException(e);
			}
		}
		
		public void sing() {
			try {
				if(status) {
					caller.ring();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("sing");
		}
		
		public void doMonitor() {
			this.sing();
			super.doMonitor();
			this.sing();
			RFIDDoReadService.setStatus(false);
		}

		public static void setStatus(boolean status) {
			RFIDDoReadService.status = status;
		}
	}
	
	public static RFIDReadInfoService getInstance() {
		return instance;
	}
	
	private RFIDReadInfoService() {
		utils = MapperUtils.getInstance();
		this.logListeners.add(new TraceInfoDataSyncListener());
		
	}
	/**
	 * 标记当前线程状态
	 * 其中：
	 * 		运行状态为：1,返回：ture
	 * 		停止状态为：2,返回：false
	 * @return
	 */
	public boolean getState() {
		if(1 == state) {
			return true;
		}
		return false;
	}
	
	/**
	 * 启动线程
	 */
	public void start() {
		synchronized (state) {
			state = RUNNING;
			thread = new Thread(this);
			thread.start();
			while(true) {
				if(thread.isAlive()) {
					break;
				}
			}
		}
	}
	
	/**
	 * 停止线程
	 */
	public void stop() {
		synchronized (state) {
			state = STOP;
		}
	}
	
	protected void doMonitor() {
		System.out.println("start to read");
		Product product = null;
		TraceInfo info = null;

		try {
			product = (Product) utils.getMapper().readAsObject(Product.class, new ProductFieldMapperToRead());
			info = (TraceInfo) utils.getMapper().readAsObject(TraceInfo.class, new TraceInfoFieldMapperToRead());
			RFIDDoReadService.setStatus(true);
		} catch (EntityMapperException e) {
			if(e instanceof EntityStatusException) {
				EntityStatusException ex = (EntityStatusException) e;
				if(-1 == ex.getReStatus()) {
					log.error("has something error to read,please try again");
				}else {
					RFIDDoReadService.setStatus(false);
				}
			}else {
				log.error("reading happen error"+e.getMessage());
				throw new ClientException("read error has happened, because :" + e.getMessage());
			}
		}
		if(null != info && null != product) {
			TraceInfo traceInfo = RFIDSaveInfoService.getInfo();
			if(null != traceInfo) {
				String[] fieldNames = {"number","address","recordTime","description"};
				RFIDSynchronismInfoService syn = new RFIDSynchronismInfoService();
				if(!syn.isEquals(traceInfo,info,fieldNames)) {
					 RFIDWriteInfoService write = new RFIDWriteInfoService();
					 write.writeInfo(traceInfo);
				}
			}else {
				JOptionPane.showMessageDialog(null, "请先设置写入值,再开始同步");
				this.state = STOP;
			}
			LogEvent eventField = new LogEvent();
			eventField.setProductNum(product.getProductNum());
			eventField.setName(product.getName());
			eventField.setNumber(traceInfo.getNumber());
			eventField.setAddress(traceInfo.getAddress());
			eventField.setRecordTime(traceInfo.getRecordTime());
			eventField.setDescription(traceInfo.getDescription());
			for(LogListener l : logListeners) {
				l.onLogEvent(eventField);
			}
		}
		
	}

	/**
	 * 读监听
	 */
	@Override
	public void run() {
		while(state == RUNNING) {
			doMonitor();
			try {
				Thread.sleep(800);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @return the logListeners
	 */
	public List<LogListener> getLogListeners() {
		return logListeners;
	}

	/**
	 * @param logListeners the logListeners to set
	 */
	public void setLogListeners(List<LogListener> logListeners) {
		this.logListeners = logListeners;
	}

	
}
